利用Python如何制作贪吃蛇及AI版贪吃蛇详解

您所在的位置:网站首页 pygame ai 贪吃蛇 利用Python如何制作贪吃蛇及AI版贪吃蛇详解

利用Python如何制作贪吃蛇及AI版贪吃蛇详解

2023-04-19 01:43| 来源: 网络整理| 查看: 265

用python制作普通贪吃蛇

哈喽,大家不知道是上午好还是中午好还是下午好还是晚上好!

贪吃蛇,应该是90后小时候的记忆(连我这个00后也不例外),今天,我们就用python这款编程语言来实现贪吃蛇

系统:所有都可以

需导入模块:

random pygame pygame.locals sys

下载以上模块指令:

random和sys是Python自带的,我们只需要下载pygame即可

下载pygame:

在开始菜单输入“cmd”回车打开,输入``指令:pip install pygame

苹果电脑需要改成:pip3 install pygame

下载好后,打开python的shell界面,输入import pygame,回车,如果没报错,及代表安装完成。

接下来什么都不说,直接奉上代码(恕我没写注释):

import random import pygame import sys from pygame.locals import * Snakespeed = 17 Window_Width = 800 Window_Height = 500 Cell_Size = 20 # Width and height of the cells # Ensuring that the cells fit perfectly in the window. eg if cell size was # 10 and window width or windowheight were 15 only 1.5 cells would # fit. assert Window_Width % Cell_Size == 0, "Window width must be a multiple of cell size." # Ensuring that only whole integer number of cells fit perfectly in the window. assert Window_Height % Cell_Size == 0, "Window height must be a multiple of cell size." Cell_W = int(Window_Width / Cell_Size) # Cell Width Cell_H = int(Window_Height / Cell_Size) # Cellc Height White = (255, 255, 255) Black = (0, 0, 0) Red = (255, 0, 0) # Defining element colors for the program. Green = (0, 255, 0) DARKGreen = (0, 155, 0) DARKGRAY = (40, 40, 40) YELLOW = (255, 255, 0) Red_DARK = (150, 0, 0) BLUE = (0, 0, 255) BLUE_DARK = (0, 0, 150) BGCOLOR = Black # Background color UP = 'up' DOWN = 'down' # Defining keyboard keys. LEFT = 'left' RIGHT = 'right' HEAD = 0 # Syntactic sugar: index of the snake's head def main(): global SnakespeedCLOCK, DISPLAYSURF, BASICFONT pygame.init() SnakespeedCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height)) BASICFONT = pygame.font.Font('freesansbold.ttf', 18) pygame.display.set_caption('Snake') showStartScreen() while True: runGame() showGameOverScreen() def runGame(): # Set a random start point. startx = random.randint(5, Cell_W - 6) starty = random.randint(5, Cell_H - 6) wormCoords = [{'x': startx, 'y': starty}, {'x': startx - 1, 'y': starty}, {'x': startx - 2, 'y': starty}] direction = RIGHT # Start the apple in a random place. apple = getRandomLocation() while True: # main game loop for event in pygame.event.get(): # event handling loop if event.type == QUIT: terminate() elif event.type == KEYDOWN: if (event.key == K_LEFT) and direction != RIGHT: direction = LEFT elif (event.key == K_RIGHT) and direction != LEFT: direction = RIGHT elif (event.key == K_UP) and direction != DOWN: direction = UP elif (event.key == K_DOWN) and direction != UP: direction = DOWN elif event.key == K_ESCAPE: terminate() # check if the Snake has hit itself or the edge if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == Cell_H: return # game over for wormBody in wormCoords[1:]: if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']: return # game over # check if Snake has eaten an apply if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']: # don't remove worm's tail segment apple = getRandomLocation() # set a new apple somewhere else: del wormCoords[-1] # remove worm's tail segment # move the worm by adding a segment in the direction it is moving if direction == UP: newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] - 1} elif direction == DOWN: newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] + 1} elif direction == LEFT: newHead = {'x': wormCoords[HEAD][ 'x'] - 1, 'y': wormCoords[HEAD]['y']} elif direction == RIGHT: newHead = {'x': wormCoords[HEAD][ 'x'] + 1, 'y': wormCoords[HEAD]['y']} wormCoords.insert(0, newHead) DISPLAYSURF.fill(BGCOLOR) drawGrid() drawWorm(wormCoords) drawApple(apple) drawScore(len(wormCoords) - 3) pygame.display.update() SnakespeedCLOCK.tick(Snakespeed) def drawPressKeyMsg(): pressKeySurf = BASICFONT.render('Press a key to play.', True, White) pressKeyRect = pressKeySurf.get_rect() pressKeyRect.topleft = (Window_Width - 200, Window_Height - 30) DISPLAYSURF.blit(pressKeySurf, pressKeyRect) def checkForKeyPress(): if len(pygame.event.get(QUIT)) > 0: terminate() keyUpEvents = pygame.event.get(KEYUP) if len(keyUpEvents) == 0: return None if keyUpEvents[0].key == K_ESCAPE: terminate() return keyUpEvents[0].key def showStartScreen(): titleFont = pygame.font.Font('freesansbold.ttf', 100) titleSurf1 = titleFont.render('Snake!', True, White, DARKGreen) degrees1 = 0 degrees2 = 0 while True: DISPLAYSURF.fill(BGCOLOR) rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1) rotatedRect1 = rotatedSurf1.get_rect() rotatedRect1.center = (Window_Width / 2, Window_Height / 2) DISPLAYSURF.blit(rotatedSurf1, rotatedRect1) drawPressKeyMsg() if checkForKeyPress(): pygame.event.get() # clear event queue return pygame.display.update() SnakespeedCLOCK.tick(Snakespeed) degrees1 += 3 # rotate by 3 degrees each frame degrees2 += 7 # rotate by 7 degrees each frame def terminate(): pygame.quit() sys.exit() def getRandomLocation(): return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)} def showGameOverScreen(): gameOverFont = pygame.font.Font('freesansbold.ttf', 100) gameSurf = gameOverFont.render('Game', True, White) overSurf = gameOverFont.render('Over', True, White) gameRect = gameSurf.get_rect() overRect = overSurf.get_rect() gameRect.midtop = (Window_Width / 2, 10) overRect.midtop = (Window_Width / 2, gameRect.height + 10 + 25) DISPLAYSURF.blit(gameSurf, gameRect) DISPLAYSURF.blit(overSurf, overRect) drawPressKeyMsg() pygame.display.update() pygame.time.wait(500) checkForKeyPress() # clear out any key presses in the event queue while True: if checkForKeyPress(): pygame.event.get() # clear event queue return def drawScore(score): scoreSurf = BASICFONT.render('Score: %s' % (score), True, White) scoreRect = scoreSurf.get_rect() scoreRect.topleft = (Window_Width - 120, 10) DISPLAYSURF.blit(scoreSurf, scoreRect) def drawWorm(wormCoords): for coord in wormCoords: x = coord['x'] * Cell_Size y = coord['y'] * Cell_Size wormSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size) pygame.draw.rect(DISPLAYSURF, DARKGreen, wormSegmentRect) wormInnerSegmentRect = pygame.Rect( x + 4, y + 4, Cell_Size - 8, Cell_Size - 8) pygame.draw.rect(DISPLAYSURF, Green, wormInnerSegmentRect) def drawApple(coord): x = coord['x'] * Cell_Size y = coord['y'] * Cell_Size appleRect = pygame.Rect(x, y, Cell_Size, Cell_Size) pygame.draw.rect(DISPLAYSURF, Red, appleRect) def drawGrid(): for x in range(0, Window_Width, Cell_Size): # draw vertical lines pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, Window_Height)) for y in range(0, Window_Height, Cell_Size): # draw horizontal lines pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (Window_Width, y)) if __name__ == '__main__': try: main() except SystemExit: pass

以上是贪吃蛇的全部代码,接下来,我们来制作AI版贪吃蛇。

用python制作AI版贪吃蛇

AI版贪吃蛇,即让系统自己玩贪吃蛇,一句话:自己玩自己。下面开始:

系统:什么都可以

需导入的模块:

pygame sys time random

如果你已经下载好了pygame,即可直接开始。

还是什么都不说,直接奉上代码(这次有注释)

#coding: utf-8 import pygame,sys,time,random from pygame.locals import * # 定义颜色变量 redColour = pygame.Color(255,0,0) blackColour = pygame.Color(0,0,0) whiteColour = pygame.Color(255,255,255) greenColour = pygame.Color(0,255,0) headColour = pygame.Color(0,119,255) #注意:在下面所有的除法中,为了防止pygame输出偏差,必须取除数(//)而不是单纯除法(/) # 蛇运动的场地长宽,因为第0行,HEIGHT行,第0列,WIDTH列为围墙,所以实际是13*13 HEIGHT = 15 WIDTH = 15 FIELD_SIZE = HEIGHT * WIDTH # 蛇头位于snake数组的第一个元素 HEAD = 0 # 用数字代表不同的对象,由于运动时矩阵上每个格子会处理成到达食物的路径长度, # 因此这三个变量间需要有足够大的间隔(>HEIGHT*WIDTH)来互相区分 # 小写一般是坐标,大写代表常量 FOOD = 0 UNDEFINED = (HEIGHT + 1) * (WIDTH + 1) SNAKE = 2 * UNDEFINED # 由于snake是一维数组,所以对应元素直接加上以下值就表示向四个方向移动 LEFT = -1 RIGHT = 1 UP = -WIDTH#一维数组,所以需要整个宽度都加上才能表示上下移动 DOWN = WIDTH # 错误码 ERR = -2333 # 用一维数组来表示二维的东西 # board表示蛇运动的矩形场地 # 初始化蛇头在(1,1)的地方 # 初始蛇长度为1 board = [0] * FIELD_SIZE #[0,0,0,……] snake = [0] * (FIELD_SIZE+1) snake[HEAD] = 1*WIDTH+1 snake_size = 1 # 与上面变量对应的临时变量,蛇试探性地移动时使用 tmpboard = [0] * FIELD_SIZE tmpsnake = [0] * (FIELD_SIZE+1) tmpsnake[HEAD] = 1*WIDTH+1 tmpsnake_size = 1 # food:食物位置初始在(4, 7) # best_move: 运动方向 food = 4 * WIDTH + 7 best_move = ERR # 运动方向数组,游戏分数(蛇长) mov = [LEFT, RIGHT, UP, DOWN] score = 1 # 检查一个cell有没有被蛇身覆盖,没有覆盖则为free,返回true def is_cell_free(idx, psize, psnake): return not (idx in psnake[:psize]) # 检查某个位置idx是否可向move方向运动 def is_move_possible(idx, move): flag = False if move == LEFT: #因为实际范围是13*13,[1,13]*[1,13],所以idx为1时不能往左跑,此时取余为1所以>1 flag = True if idx%WIDTH > 1 else False elif move == RIGHT: #这里的 (2*WIDTH-1) else False elif move == DOWN: flag = True if idx < (FIELD_SIZE-2*WIDTH) else False return flag # 重置board # board_BFS后,UNDEFINED值都变为了到达食物的路径长度 # 如需要还原,则要重置它 def board_reset(psnake, psize, pboard): for i in range(FIELD_SIZE): if i == food: pboard[i] = FOOD elif is_cell_free(i, psize, psnake): # 该位置为空 pboard[i] = UNDEFINED else: # 该位置为蛇身 pboard[i] = SNAKE # 广度优先搜索遍历整个board, # 计算出board中每个非SNAKE元素到达食物的路径长度 def board_BFS(pfood, psnake, pboard): queue = [] queue.append(pfood) inqueue = [0] * FIELD_SIZE found = False # while循环结束后,除了蛇的身体, # 其它每个方格中的数字为从它到食物的曼哈顿间距 while len(queue)!=0: idx = queue.pop(0)#初始时idx是食物的坐标 if inqueue[idx] == 1: continue inqueue[idx] = 1 for i in range(4):#左右上下 if is_move_possible(idx, mov[i]): if idx + mov[i] == psnake[HEAD]: found = True if pboard[idx+mov[i]] < SNAKE: # 如果该点不是蛇的身体 if pboard[idx+mov[i]] > pboard[idx]+1:#小于的时候不管,不然会覆盖已有的路径数据 pboard[idx+mov[i]] = pboard[idx] + 1 if inqueue[idx+mov[i]] == 0: queue.append(idx+mov[i]) return found # 从蛇头开始,根据board中元素值, # 从蛇头周围4个领域点中选择最短路径 def choose_shortest_safe_move(psnake, pboard): best_move = ERR min = SNAKE for i in range(4): if is_move_possible(psnake[HEAD], mov[i]) and pboard[psnake[HEAD]+mov[i]]3: result = False return result # 让蛇头朝着蛇尾运行一步 # 不管蛇身阻挡,朝蛇尾方向运行 def follow_tail(): global tmpboard, tmpsnake, food, tmpsnake_size tmpsnake_size = snake_size tmpsnake = snake[:] board_reset(tmpsnake, tmpsnake_size, tmpboard) # 重置虚拟board tmpboard[tmpsnake[tmpsnake_size-1]] = FOOD # 让蛇尾成为食物 tmpboard[food] = SNAKE # 让食物的地方变成蛇身 board_BFS(tmpsnake[tmpsnake_size-1], tmpsnake, tmpboard) # 求得各个位置到达蛇尾的路径长度 tmpboard[tmpsnake[tmpsnake_size-1]] = SNAKE # 还原蛇尾 return choose_longest_safe_move(tmpsnake, tmpboard) # 返回运行方向(让蛇头运动1步) # 在各种方案都不行时,随便找一个可行的方向来走(1步), def any_possible_move(): global food , snake, snake_size, board best_move = ERR board_reset(snake, snake_size, board) board_BFS(food, snake, board) min = SNAKE for i in range(4): if is_move_possible(snake[HEAD], mov[i]) and board[snake[HEAD]+mov[i]]


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3